import React, { Component } from "react";
import "./Style.less";
import service from "../service";

class TodoList extends Component {
  state = {
    list: [],
    input: "",
  };
  // componentDidMount() {
  //   this.getList();
  // }
  getList = async () => {
    let token = localStorage.getItem("token");
    let uid = localStorage.getItem("id");
    let res = await service.GetList(token, uid);
    console.log(res);
    this.state.list = res.list;
    this.setState({});
  };
  add = async () => {
    let token = localStorage.getItem("token");
    let uid = localStorage.getItem("id");
    let res = await service.Add(token,uid,this.state.input,);
    console.log(res);
    this.getList();
  };
  Del = async (id) => {
    let token = localStorage.getItem("token");
    let res = await service.Del(token, id);
    console.log(res);
    this.getList();
  };
  update = async (id) => {
    let token = localStorage.getItem("token");
    let res = await service.Update(token, id);
    console.log(res);
    this.getList();
  };
  render() {
    return (
      <div className="TodoList">
        <div>
          <input
            className="input"
            placeholder="请输入事项名称..."
            type="text"
            value={this.state.input}
            onChange={(e) => {
              this.setState({ input: e.target.value });
            }}
          />
          <button className="b1" onClick={this.add}>
            提交
          </button>
          <button onClick={this.getList}>获取列表</button>
        </div>
        <ul className="listborder">
          {this.state.list.map((item, index) => {
            return (
              <li key={index}>
                {item.matter}
                <button className="b2" onClick={this.Del.bind(null, item._id)}>
                  删除
                </button>
                {item.state ? (
                  <span>已完成</span>
                ) : (
                  <button
                    className="b3"
                    onClick={this.update.bind(null, item._id)}
                  >
                    完成
                  </button>
                )}
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default TodoList;
